<template>
  <a-drawer
      :title="title"
      :mask-closable="true"
      :width="drawerWidth"
      placement="right"
      :visible="visible"
      :closable="true"
      @close="handleCancel"
      style="height: 100%;overflow: auto;padding-bottom: 53px;">

    <a-spin :spinning="confirmLoading">
      <a-form-model ref="formRef" :model="model" :rules="validatorRules">

        <a-form-model-item label="用户账号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="username">
          <a-input placeholder="请输入用户账号" v-model="model.username" :readOnly="!!model.id"/>
        </a-form-model-item>

        <template v-if="!model.id">
          <a-form-model-item label="登录密码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="password" >
            <a-input type="password" placeholder="请输入登录密码" v-model="model.password" />
          </a-form-model-item>

          <a-form-model-item label="确认密码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="confirmPassword" >
            <a-input type="password" @blur="handleConfirmBlur" placeholder="请重新输入登录密码" v-model="model.confirmPassword"/>
          </a-form-model-item>
        </template>

        <a-form-model-item label="用户姓名" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="realName">
          <a-input placeholder="请输入用户姓名" v-model="model.realName" />
        </a-form-model-item>

        <a-form-model-item label="头像" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="avatar">
          <image-upload class="avatar-uploader" text="上传" v-model="model.avatar" :image-multiple="false"/>
        </a-form-model-item>
      </a-form-model>
      <a-form-model-item label="邮箱" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="email">
        <a-input placeholder="请输入邮箱" v-model="model.email" />
      </a-form-model-item>

      <a-form-model-item label="手机号码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="phone">
        <a-input placeholder="请输入手机号码" v-model="model.phone" />
      </a-form-model-item>

      <a-form-model-item label="用户角色" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="roles">
        <g-multi-select dict-code="sys_role,id,role_name" v-model="model.roles" placeholder="请选择用户角色"/>
      </a-form-model-item>
    </a-spin>

    <div class="drawer-bootom-button" v-show="!disableSubmit">
      <a-popconfirm title="确定放弃编辑？" @confirm="handleCancel" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit" type="primary" :loading="confirmLoading">提交</a-button>
    </div>
  </a-drawer>

</template>

<script>
import {Table,Tabs,Modal,FormModel,Form} from 'ant-design-vue'
import ImageUpload from "@comp/ImageUpload";
import GMultiSelect from "@comp/GMultiSelect";
import {postAction} from "@api/manage";
import {DrawerFormMixin} from "@/mixins/DrawerFormMixin";

export default {
  name: "UserModules",
  components: {
    Table,
    Tabs,
    Modal,
    FormModel,
    Form,
    ImageUpload,
    GMultiSelect,
  },
  mixins: [DrawerFormMixin],
  data() {
    return {
      disableSubmit:false,
      validatorRules:{
        username:[
          {required: true, message: '请输入用户账号!'},
          {validator: this.validateUsername,}
        ],
        password: [
            { required: true,
              pattern:/^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,./]).{8,}$/,
              message: '密码由8位数字、大小写字母和特殊符号组成!'
            },
            { validator: this.validateToNextPassword,
              trigger: 'change'
            }
        ],
        confirmPassword: [
            {required: true, message: '请重新输入登录密码!',},
            {validator: this.compareToFirstPassword,}
        ],
        realName:[
            { required: true, message: '请输入用户名称!' }
        ],
        phone: [
            { validator: this.validatePhone }
        ],
        email: [
            { validator: this.validateEmail }
        ],
        roles:{},
        avatar:{},
      },
      url: {
        add: '/user/add',
        edit: '/user/edit'
      }
    }
  },
  methods: {

    add(){
      this.model = {};
      this.resetScreenSize();
      this.visible = true;
    },

    edit(record){
      console.info("record",record);
      this.resetScreenSize();
      this.model = Object.assign({},record);
      console.info('model',this.model)
      this.visible = true;
    },

    // 根据屏幕变化,设置抽屉尺寸
    resetScreenSize(){
      let screenWidth = document.body.clientWidth;
      if(screenWidth < 500){
        this.drawerWidth = screenWidth;
      }else{
        this.drawerWidth = 700;
      }
    },

    handleConfirmBlur(e) {
      const value = e.target.value;
      this.confirmDirty = this.confirmDirty || !!value
    },


    validateUsername(rule, value, callback){
      let params = {
        'tableName':'sys_user',
        'valueField':'username',
        'value':value,
        'id': this.model.id || null
      };
      postAction(`/common/duplicateCheck`,params).then((res) => {
        if (res.success) {
          callback()
        } else {
          callback("用户名已存在!")
        }
      })
    },

    validateEmail(rule, value, callback){
      if(!value){
        callback()
      }else{
        if(new RegExp(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/).test(value)){
          callback()
        }else{
          callback("请输入正确格式的邮箱!")
        }
      }
    },

    validatePhone(rule, value, callback){
      if(!value){
        callback()
      }else{
        if(new RegExp(/^1[3|4|5|7|8|9][0-9]\d{8}$/).test(value)){
          callback()
        }else{
          callback("请输入正确格式的手机号码!");
        }
      }
    },

    validateToNextPassword (rule, value, callback) {
      const confirmPassword=this.model.confirmPassword;
      if (value && confirmPassword && value !== confirmPassword) {
        callback('两次输入的密码不一样！');
      }
      if (value && this.confirmDirty) {
        this.$refs['formRef'].validateField(['confirmPassword']);
      }
      callback();
    },

    compareToFirstPassword (rule, value, callback) {
      if (value && value !== this.model.password) {
        callback('两次输入的密码不一样！');
      } else {
        callback()
      }
    },
  }
}
</script>

<style scoped>

</style>
